package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("FeaturestandardService")
@Transactional

public class FeaturestandardServiceImpl extends CmiEmaService implements FeaturestandardService {
	public FeaturestandardServiceImpl() {
	}

	@Transactional
	public Featurestandard saveFeaturestandard(Featurestandard featurestandard) {

		if (featurestandard.getId() == null) {
			Feature feature = featureDAO.findFeatureById(featurestandard.getFeature().getId());
			Standard standard = standardDAO.findStandardById(featurestandard.getStandard().getId());
			Unit unit = unitDAO.findUnitById(featurestandard.getUnit().getId());

			Featurestandard existingFeaturestandard = featurestandardDAO
					.findFeaturestandardByPhysicalPrimaryKey(unit.getId(), standard.getId(), feature.getId());

			featurestandard.setFeature(feature);
			featurestandard.setStandard(standard);
			featurestandard.setUnit(unit);

			if (isEquals(featurestandard, existingFeaturestandard)) {
				return existingFeaturestandard;
			}

			featurestandard = featurestandardDAO.store(featurestandard);
			featurestandardDAO.flush();

		} else {
			Featurestandard existingFeaturestandard = featurestandardDAO
					.findFeaturestandardByPrimaryKey(featurestandard.getId());

			featurestandard = featurestandardDAO.store(featurestandard);
			featurestandardDAO.flush();
		}

		return featurestandard;
	}

	public void deleteFeaturestandard(Featurestandard featurestandard) {
		featurestandardDAO.remove(featurestandard);
		featurestandardDAO.flush();
	}

	@Transactional
	public void deleteFeaturestandards(Set<Integer> deleteFeaturestandardsId) {
		Query query = featurestandardDAO.createNamedQuery("deleteFeaturestandardsById", -1, -1);
		query.setParameter(1, deleteFeaturestandardsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Featurestandard> loadFeaturestandards() {
		return featurestandardDAO.findAllFeaturestandards();

	}

	@Transactional
	public Set<Featurestandard> loadReferenceFeaturestandards(Set<Featurestandard> featurestandards) {
		Iterator<Featurestandard> featurestandardsIterator = featurestandards.iterator();
		Set<Featurestandard> referencedFeaturestandards = new HashSet<>();
		while (featurestandardsIterator.hasNext()) {
			Featurestandard currentFeaturestandard = featurestandardsIterator.next();

		}
		return referencedFeaturestandards;
	}

	public Set<Featurestandard> loadFeaturestandardsByIdSet(Set<Integer> featurestandardIdSet) {

		Iterator<Integer> featurestandardIdIterator = featurestandardIdSet.iterator();
		Set<Featurestandard> featurestandardSet = new HashSet<>();
		while (featurestandardIdIterator.hasNext()) {
			Integer id = featurestandardIdIterator.next();
			Featurestandard currentFeaturestandard = featurestandardDAO.findFeaturestandardById(id);
			featurestandardSet.add(currentFeaturestandard);
		}
		return featurestandardSet;
	}

	@Transactional
	public List<Featurestandard> findAllFeaturestandards(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Featurestandard>(
				featurestandardDAO.findAllFeaturestandards(startResult, maxRows));
	}

	@Transactional
	public Featurestandard findFeaturestandardByPrimaryKey(Integer id) {
		return featurestandardDAO.findFeaturestandardByPrimaryKey(id);
	}

	@Transactional
	public Integer countFeaturestandards() {
		return ((Long) featurestandardDAO.createQuerySingleResult("select count(o) from Featurestandard o")
				.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countFeaturestandards(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Featurestandard.class);
		return ((Long) featurestandardDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countFeaturestandardsByName(String queryName) {
		Query query = featurestandardDAO.createNamedQuery("countFeaturestandardsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countFeaturestandardsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Featurestandard.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadFeaturestandardObjectReferencedSet(Featurestandard featurestandard) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (featurestandard.getFeature() != null) {

			Set<Integer> featureIds = new HashSet<Integer>();
			featureIds.add(featurestandard.getFeature().getId());
			objectReferencedSetMap.put("featureIds", featureIds);
		}
		if (featurestandard.getStandard() != null) {

			Set<Integer> standardIds = new HashSet<Integer>();
			standardIds.add(featurestandard.getStandard().getId());
			objectReferencedSetMap.put("standardIds", standardIds);
		}
		if (featurestandard.getUnit() != null) {

			Set<Integer> unitIds = new HashSet<Integer>();
			unitIds.add(featurestandard.getUnit().getId());
			objectReferencedSetMap.put("unitIds", unitIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadFeaturestandardClassReferencedSet(Featurestandard featurestandard) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("features", featureDAO.findAllFeatures());
		classReferencedSetMap.put("standards", standardDAO.findAllStandards());
		classReferencedSetMap.put("units", unitDAO.findAllUnits());

		return classReferencedSetMap;
	}

	public boolean isEquals(Featurestandard featurestandard, Object obj) {
		if (obj == featurestandard)
			return true;
		if (!(obj instanceof Featurestandard))
			return false;
		Featurestandard comparedFeaturestandard = (Featurestandard) obj;
		if (!CheckPropertyEqual(featurestandard.getUnit().getId(), comparedFeaturestandard.getUnit().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(featurestandard.getStandard().getId(), comparedFeaturestandard.getStandard().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(featurestandard.getFeature().getId(), comparedFeaturestandard.getFeature().getId())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

